//网络请求和json解析练习

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_practice/utils/Utils.dart';
import 'package:http/http.dart' as http;

class MyNetAndJSonDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyNetAndJsonState();
  }
}

class MyNetAndJsonState extends State<MyNetAndJSonDemo> {
  MyNetEntity entity;
  var _con = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: Utils.getAppBar('网络案例'),
      body: Center(
        child: Column(
          children: <Widget>[
            CircleAvatar(
              child: Icon(Icons.save),
            ),
            ListTile(
              leading: Icon(Icons.person),
              title: Text(
                'name: ' +
                    (entity != null && entity.name != null
                        ? entity.name
                        : '暂无'),
              ),
            ),
            ListTile(
              leading: Icon(Icons.location_city),
              title: Text(
                'name: ' +
                    (entity != null && entity.location != null
                        ? entity.location
                        : '暂无'),
              ),
            ),
            ListTile(
              leading: Icon(Icons.web),
              title: Text(
                'name: ' +
                    (entity != null && entity.blog != null
                        ? entity.blog
                        : '暂无'),
              ),
            ),
            TextField(
              controller: _con,
              decoration:
                  InputDecoration(icon: Icon(Icons.title), labelText: '输入github 用户名'),
            ),
            RaisedButton(
              onPressed: () {
                getUserInfo(_con.value.text.toString());
              },
              child: Text('get请求'),
            )
          ],
        ),
      ),
    );
  }

  void getUserInfo(String username) {
    http.get("https://api.github.com/users/$username").then((reponse) {
      setState(() {
        final resJson = json.decode(reponse.body);
        entity = new MyNetEntity.fromJson(resJson);
        print('entity: ' + entity.name);
      });
    }).catchError((error) {
      print(error.toString());
    }).whenComplete(() {
      print('请求完成');
    });
  }
}

class MyNetEntity {
  String name;
  String location;
  String blog;
  String htmlUrl;
  String avaUrl;

  MyNetEntity({this.name, this.location, this.blog, this.htmlUrl, this.avaUrl});

  factory MyNetEntity.fromJson(Map<String, dynamic> json) {
    return MyNetEntity(
      name: json['name'],
      location: json['location'],
      blog: json['blog'],
      htmlUrl: json['html_url'],
      avaUrl: json['avatar_url'],
    );
  }
}
